package com.huishi.handler.ws;

/**
 *
 */
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/webSocket/{topic}")
@Slf4j
public class WebSocketServer {
    private Session session;
    private String topic;
    /**静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。*/
    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * concurrent包的线程安全set，用来存放每个客户端对应的MyWebSocket对象
     */
    private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap();

    /**
     * 为了保存在线用户信息，在方法中新建一个list存储一下【实际项目依据复杂度，可以存储到数据库或者缓存】
     */
    private final static List<Session> SESSIONS = Collections.synchronizedList(new ArrayList<>());

    /**
     * 建立连接
     * @param session
     * @param topic
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("topic") String topic) {
        this.session = session;
        this.topic = topic;
        webSocketSet.add(this);
        SESSIONS.add(session);
        if (webSocketMap.containsKey(topic)) {
            webSocketMap.remove(topic);
            webSocketMap.put(topic,this);
        } else {
            webSocketMap.put(topic,this);
            addOnlineCount();
        }
        // log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
        log.info("[连接topic:{}] 建立连接, 当前连接数:{}", this.topic, webSocketMap.size());
    }

    /**
     * 断开连接
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        if (webSocketMap.containsKey(topic)) {
            webSocketMap.remove(topic);
            subOnlineCount();
        }
        // log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
        log.info("[连接topic:{}] 断开连接, 当前连接数:{}", topic, webSocketMap.size());
    }

    /**
     * 发送错误
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.info("[连接topic:{}] 错误原因:{}", this.topic, error.getMessage());
        error.printStackTrace();
    }

    /**
     * 收到消息
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        // log.info("【websocket消息】收到客户端发来的消息:{}", message);
        log.info("[连接topic:{}] 收到消息:{}", this.topic, message);
    }

    /**
     * 发送消息
     * @param message
     * @param topic
     */
    public void sendMessage(String message,String topic) {
        WebSocketServer webSocketServer = webSocketMap.get(topic);
        if (webSocketServer!=null){
            log.info("【websocket消息】推送消息, message={}", message);
            try {
                webSocketServer.session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("[连接topic:{}] 发送消息失败, 消息:{}", this.topic, message, e);
            }
        }
    }

    /**
     * 群发消息
     * @param message
     */
    public void sendMassMessage(String message) {
        try {
            for (Session session : SESSIONS) {
                if (session.isOpen()) {
                    session.getBasicRemote().sendText(message);
                    log.info("[连接topic:{}] 发送消息:{}",session.getRequestParameterMap().get("topic"),message);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前连接数
     * @return
     */
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    /**
     * 当前连接数加一
     */
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    /**
     * 当前连接数减一
     */
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}
